<template>
  <div class="cg-image-select">
    <img class="cg-image-content" :src="imageData" />
    <cg-button type="text" @click="handleSelect">选择</cg-button>
    <cg-dialog v-model:visible="visible" title="选择图片">
      <div :style="{ maxHeight: '50vh', overflow: 'auto' }">
        <cg-gird :column="{ gutter: 10, colNum }">
          <cg-gird-item
            v-for="(item, index) in options"
            :key="index"
            :class="{ active: selectPath === item.path }"
            @click="selectPath = item.path"
          >
            <img :src="item.data" />
          </cg-gird-item>
        </cg-gird>
      </div>

      <template v-slot:footer>
        <cg-button @click="selectAction">确定</cg-button>
      </template>
    </cg-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { switchValue } from '../../tools/index'

// 定义组件名称
defineOptions({
  name: 'cg-image-select'
})

// 定义props
const props = withDefaults(
  defineProps<{
    modelValue: string
    options: Array<{
      path: string
      data: string
      [key: string]: any
    }>
    colNum: number
  }>(),
  {
    colNum: 3
  }
)

// 定义emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
}>()

// 响应式数据
const visible = ref(false)
const selectPath = ref<string | undefined>(props.modelValue)

// 计算属性
const imageData = computed(() => {
  return switchValue(props.modelValue, props.options, 'path').data
})

// 监听modelValue变化
watch(
  () => props.modelValue,
  (val) => {
    selectPath.value = val
  },
  { immediate: true }
)

// 方法
const selectAction = () => {
  if (selectPath.value !== undefined) {
    emit('update:modelValue', selectPath.value)
  }
  visible.value = false
}

const handleSelect = () => {
  visible.value = true
  selectPath.value = props.modelValue
}
</script>

<style lang="scss">
.cg-image-select {
  .cg-image-content {
    height: 100px;
  }

  .cg-gird {
    .cg-gird-item {
      font-size: 0;
      padding: 2px;
      cursor: pointer;

      &.active {
        border-color: #409eff;
        box-shadow:
          0 0 8px 0 rgba(64, 158, 255, 0.6),
          0 2px 4px 0 rgba(64, 158, 255, 0.5);
      }

      img {
        width: 100%;
      }
    }
  }
}
</style>
